# Create your views here.
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from blog.models import Entries, Categories, TagModel, Comments, Users
from django.template import Context, loader
from django.views.decorators.csrf import csrf_exempt

#from hashlib import md5

@csrf_exempt
def index(request, page=1):
    import md5
    #page_title = '블로그 글 목록 화면'
    
    user_id = request.POST['userid']
    user_password = request.POST['password']
    
    try:
        users = Users.objects.get(userid = user_id);
    except:
        return HttpResponse('아이디 또는 비밀번호가 틀렸습니다.')

    if md5.md5(user_password).hexdigest() != users.Password:
        return HttpResponse('아이디 또는 비밀번호가 틀렸습니다.')
    
    per_page = 5
    start_pos = (page - 1) * per_page
    end_pos = start_pos + per_page
    
    page_title = '블로그 글 목록 화면'
    
    #entries = Entries.objects.all()[start_pos:end_pos]
    entries = Entries.objects.all().order_by('-created')[start_pos:end_pos]
    
    #return HttpResponse('안녕, 여러분. 여긴 [%s]이고 첫번째 글이야.' %entries[0].Title.encode('utf-8'))
    
    
    tpl = loader.get_template('list.html')
    
    ctx = Context({'page_title':page_title,
                   'entries':entries,
                   'current_page':page,
    })
    
    return HttpResponse(tpl.render(ctx))
    
def read(request, entry_id=None):
    
    page_title = '블로그 글 목록 화면'
    
    #current_entry = Entries.objects.get(id=int(entry_id))
    
    try:
        current_entry = Entries.objects.get(id=int(entry_id))
    except:
        return HttpResponse('글이 존재하지 않습니다.')
    
    try:
        prev_entry = current_entry.get_previous_by_created()
    except:
        prev_entry = None
        
    try:
        next_entry = current_entry.get_next_by_created()
    except:
        next_entry = None
    
    try:
        comments = Comments.objects.filter(Entry=current_entry).order_by('created')
    except:
        comments = None
     
    #comments = Comments.objects.filter(Entry=entry_id).order_by('created')

    #return HttpResponse('안녕, 여러분. [%d]번 글은 [%s]야.' %(current_entry.id, current_entry.Title.encode('utf-8')))
   
    
    
    
    
    
    tpl = loader.get_template('read.html')
    
    ctx = Context({'page_title':page_title,
                   'current_entry':current_entry,
                   'prev_entry':prev_entry,
                   'next_entry':next_entry,
                   'comments':comments,
    })
    
    
    
    return HttpResponse(tpl.render(ctx))

def write_form(request):
    
    page_title = '블로그 글 목록 화면'
    
    tpl = loader.get_template('write.html')
    
    categories = Categories.objects.all() 
    
    
    ctx = Context({'page_title':page_title,
                   'categories':categories
    })
    
    
    return HttpResponse(tpl.render(ctx))

@csrf_exempt #CSRF 오류날때 from django.views.decorators.csrf import csrf_exempt 함께 사용
def add_post(request):
    
    if request.POST.has_key('title') == False:
        return HttpResponse('글 제목을 입력해야 한다우')
    else:
        if len(request.POST['title']) == 0:
            return HttpResponse('글 제목엔 적어도 한 글자는 넣자!')
        else:
            entry_title = request.POST['title']
    
    if request.POST.has_key('content') == False:
        return HttpResponse('글 본문을 입력해야 합니다.')
    else :
        if len(request.POST['content']) == 0:
            return HttpResponse('글 본문을 적어도 한 글자는 넣자')
        else:
            entry_content = request.POST['content']
    
    try:
        entry_category = Categories.objects.get(id=request.POST['category'])
    except:
        return HttpResponse('이산한 글 갈래구려')
    
    if request.POST.has_key('tags') == True:
        tags = map(lambda str: str.strip(), unicode(request.POST['tags']).split(','))
        
        tag_list = map(lambda tag: TagModel.objects.get_or_create(Title=tag)[0], tags)
        #tag_list = []
        #for tag in tags:
        #    tag_list.append(TagModel.objects.get_or_create(Title=tag)[0])
    else:
        tag_list = []
    
    new_entry = Entries(Title=entry_title, Content=entry_content, Category=entry_category)
    new_entry.save()
    
    for tag in tag_list:
        new_entry.Tags.add(tag)
    
    if len(tag_list) > 0:
        try:
            new_entry.save()
        except:
            return HttpResponse('글을 써넣다가 오류가 발생했습니다.')
    #entry_title = request.POST['title']
    #return HttpResponse('hello %s %s' % (entry_title, entry_category.Title))
    return HttpResponse('%s번 글을 제대로 저장했습니다.' % new_entry.id)

@csrf_exempt
def add_comment(request):
    import md5
    cmt_name = request.POST.get('name', '')
    if not cmt_name.strip():
        return HttpResponse('글쓴이 이름을 입력해야 합니다.')
    
    cmt_password = request.POST.get('password', '')
    if not cmt_password.strip():
        return HttpResponse('비밀번호를 입력해야 합니다.')
    
   
    cmt_password = md5.md5(cmt_password).hexdigest()
    print cmt_password
    #mystring = "kwon"
    #print md5.md5(mystring).hexdigest()
    
    cmt_content = request.POST.get('content', '')
    if not cmt_content.strip():
        return HttpResponse('댓글 내용을 입력해야 합니다.')
    
    if request.POST.has_key('entry_id') == False:
        return HttpResponse('댓글 달 글을 지정해야 합니다.')
    else:
        try:
            entry = Entries.objects.get(id=request.POST['entry_id'])
        except:
            return HttpResponse('그런 글은 없습니다.')
    
    try:
        new_cmt = Comments(Name=cmt_name, Password=cmt_password, Content=cmt_content, Entry=entry)
        new_cmt.save()
        entry.Comments += 1
        entry.save()
        return HttpResponse('댓글을 추가 했습니다.')
    except:
        return HttpResponse('올바르게 저장이 되지 않았습니다.')
    
    return HttpResponse('문제가 생겨 저장하지 못하였습니다.')

@csrf_exempt
def del_comment(request, comment_id=None):
    import md5#request.POST['entry_id']
    #del_entry = Entries.objects.get(id=int(Comments.objects.get(comment_id))
    
    try:
        del_entry = Comments.objects.get(id=request.POST['comment_id'])
    except:
        return HttpResponse('이미 삭제되었거나 삭제를 하지 못하였습니다.')
    #comments = Comments.objects.filter(Entry=del_entry)

    if md5.md5(request.POST['password']).hexdigest() == del_entry.Password:
        del_entry.delete()
    else:
        return HttpResponse('비밀번호가 틀렸습니다.')
    #del_entry = Entries.objects.get(id=request.POST['entry_id'], Password=md5.md5(request.POST['password']) )
    return HttpResponse('삭제완료.')
    
def rssfeed(request):
    from django.utils import feedgenerator
    
    fd = feedgenerator.Rss201rev2Feed(
        title = u'my blog rss',
        link = u'/blog/feed/',
        description = u'this is a rss of my blog'
        )

    for entry in Entries.objects.all().order_by('-created')[:5]:
        fd.add_item(
            title = entry.Title,
            link = u'/blog/entry/%d/' % entry.id,
            description = entry.Content,
            pubdate = entry.created,
            categories = (entry.Category.Title) 
        )

    return HttpResponse(fd.writeString('utf-8'), mimetype='application/rss+xml')

def login(request):
    request.session['blog_login_sess'] = 'hannal'
    return HttpResponse('[%s] logged in successfully' % request.session['blog_login_sess'])

def logout(request):
    
    try:
        del request.session['blog_login_sess']
    except:
        return HttpResponse('로그인 하지 않았습니다.')
    
    return HttpResponse('logged out successfully')

def login_page1(request):
    page_title = '회원 가입 화면'
    
    tpl = loader.get_template('page1.html')
    
    users = Users.objects.all() 
    
    
    ctx = Context({'page_title':page_title,
                   'users':users,
    })
    
    
    return HttpResponse(tpl.render(ctx))

@csrf_exempt
def login_page2(request):
    import md5
    
    user_id = request.POST['name']
    print md5.md5(request.POST['password']).hexdigest()
    user_password = md5.md5(request.POST['password']).hexdigest()
    
    #try:
    new_user = Users(userid=user_id, Password=user_password)
    new_user.save()
    #except:
     #   return HttpResponse('저장되지 않았습니다.')
    #if id == Users.objects.get(id = user_id, password = user_password):
    #    return HttpResponse('가입 확인을 성공 하였습니다.')
    
    return HttpResponse('가입되었습니다.')

def login_page(request):
    page_title = '로그인 화면'
    
    tpl = loader.get_template('loginpage.html')
    
    ctx = Context({'page_title':page_title,
                   
    })
    
    
    return HttpResponse(tpl.render(ctx))
    
    